import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Button, Form, Input, Switch, Select, Radio, InputNumber, Badge, Row, Col, message, Spin } from 'antd'
import constant from "../constant";
import { deepFullCopy, messages, queryCurrencyPrecision } from "share/common";
import Priority from "components/template/priority";
import ResizeTable from "components/resize-table/resize-table";
import WrapFormItem from "components/wrap-form-item";
import LoanMaxModal from "containers/finance-setting/loan-max/loan-max-modal";
import SettingService from 'containers/finance-setting/loan-setting/setting-service'
import InputLanguage from "components/template/input-language";
import httpFetch from "share/httpFetch";
import Space from "components/space";
import VendorMaxModal from "../../loan-max/vendor-max-modal";

@connect(mapStateToProps)
class LoanRule extends Component {

  state = {
    priority: null,
    saveLoading: false,
    data: [],
    loanMaxRecord: {},
    visible: false,
    writeOffList: [],
    fetched: false,
    vendorLoanAmountMaxDTOs: [],
    vendorLoanMaxRecord: {},
    vendorVisible: false
  };

  componentWillMount() {
    const { record } = this.props.params;
    const { tenant } = this.props;
    if (record.hasOwnProperty('id')) {
      this.setState({
        priority: {
          levelOrgName: record.setOfBookName || tenant.tenantName,
          levelOrgId: record.setOfBookId !== '-1' ? record.setOfBookId : tenant.id,
          levelCode: record.setOfBookId !== '-1' ? 'SET_OF_BOOK' : 'TENANT'
        },
        data: record.loanAmountMaxDTOs || [],
        vendorLoanAmountMaxDTOs: record.vendorLoanAmountMaxDTOs || []
      }, this.getList)
    } else {
      this.setState({
        priority: {
          levelCode: 'TENANT',
          levelOrgName: tenant.tenantName,
          levelOrgId: tenant.id
        }
      }, this.getList)
    }
  }

  handleSave = () => {
    this.props.form.validateFieldsAndScroll((err, value) => {
      if (!err) {
        const { data, priority, vendorLoanAmountMaxDTOs } = this.state, { record } = this.props.params, { close, tenant } = this.props;
        if (!priority || (priority.distribution && priority.distribution.companies.length === 0)) {
          message.error(messages('finance-1.key371')/*请分配权限*/);
          return -1;
        }
        let temp = deepFullCopy(value);
        priority.levelCode === 'SET_OF_BOOK' && (temp.setOfBookId = priority.levelOrgId);
        let writeOff = temp.writeOff;
        writeOff.writeOffId && (writeOff.writeOffId = writeOff.writeOffId.join(','));
        temp.cashRepaymentTerm.repaymentControlType = temp.repaymentControlType;
        delete temp.writeOff;
        delete temp.repaymentControlType;
        let i18n = temp.description;
        if (!i18n.name) {
          message.error(messages('finance-1.key372')/*请输入借款类型名称*/);
          return -1;
        }
        temp.description = i18n.name;
        temp.i18n = {
          description: i18n.i18n
        };
        this.setState({ saveLoading: true });
        SettingService.saveLoanRule(Object.assign( record, writeOff, temp , {
          loanAmountMaxDTOs: data.map(item => Object.assign(item, { setOfBooksId: priority.levelOrgId, setOfBooksName: priority.levelOrgName })),
          vendorLoanAmountMaxDTOs: vendorLoanAmountMaxDTOs.map(item => Object.assign(item, { setOfBooksId: priority.levelOrgId, setOfBooksName: priority.levelOrgName })),
          typeCode: 'PREPAYMENT',
          tenantId: tenant.id
        })).then(() => {
          this.setState({ saveLoading: false }, () => {
            message.success(messages('common.operate.success')/*操作成功*/);
            close(true);
          });
        }).catch(e => {
          message.error(e.response.data.message);
          this.setState({ saveLoading: false });
        })
      }
    })
  };

  handlePriority = value => {
    this.props.form.setFieldsValue({ writeOff : { writeOffType: '1' } });
    this.setState({ priority: value, data: [], writeOffList: [], vendorLoanAmountMaxDTOs: [] }, () => {
      value.levelOrgId && this.getList();
    });
  };

  handleChangeType = () => {
    this.setState({ data: [], vendorLoanAmountMaxDTOs: [] });
  };

  getList = () => {
    const { priority } = this.state;
    if (priority) {
      this.setState({ fetched: true });
      httpFetch.get(`/api/cash/transaction/classes/queryPaymentTransaction/v2`, {
        setOfBooksId: priority.levelCode !== 'TENANT' ? priority.levelOrgId : undefined
      }).then(res => {
        this.setState({ writeOffList: res.data, fetched: false });
      }).catch(e => {
        message.error(e.response.data.message);
        this.setState({ fetched: false });
      });
    }
  };

  handleAddLoanMax = record => {
    this.setState({ loanMaxRecord: record }, () => {
      this.setState({ visible: true });
    })
  };

  handleAddVendorMax = record => {
    this.setState({ vendorLoanMaxRecord: record }, () => {
      this.setState({ vendorVisible: true });
    })
  };

  onOk = value => {
    const { data, loanMaxRecord } = this.state;
    if (loanMaxRecord.hasOwnProperty('id')) {
      data.splice(data.findIndex(item => item.id === value.id), 1, value)
    } else {
      let index = data.findIndex(item => item.frontId === value.frontId);
      if (index === -1) {
        data.push(value);
      } else {
        data.splice(index, 1, value);
      }
    }
    this.setState({ data, visible: false });
  };

  onVendorOk = value => {
    const { vendorLoanMaxRecord, vendorLoanAmountMaxDTOs } = this.state;
    if (vendorLoanMaxRecord.hasOwnProperty('id')) {
      vendorLoanAmountMaxDTOs.splice(vendorLoanAmountMaxDTOs.findIndex(item => item.id === value.id), 1, value)
    } else {
      let index = vendorLoanAmountMaxDTOs.findIndex(item => item.frontId === value.frontId);
      if (index === -1) {
        vendorLoanAmountMaxDTOs.push(value);
      } else {
        vendorLoanAmountMaxDTOs.splice(index, 1, value);
      }
    }
    this.setState({ vendorLoanAmountMaxDTOs, vendorVisible: false });
  };

  getRandomId = () => {
    const { data, vendorLoanAmountMaxDTOs } = this.state;
    let id = Math.ceil(Math.random() * 100000);
    if (!data.find(item => item.frontId === id) && !vendorLoanAmountMaxDTOs.find(item => item.frontId === id)) {
      return id;
    } else {
      this.getRandomId();
    }
  };

  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { saveLoading, priority, data, visible, loanMaxRecord, writeOffList, fetched, vendorLoanAmountMaxDTOs,
      vendorVisible, vendorLoanMaxRecord } = this.state;
    const { formItemLayout } = constant;
    const { close } = this.props, { record } = this.props.params;
    return (
      <div>
        <Form className={'new-form'}>
          <Form.Item
            label={messages('common.column.status')/*状态*/}
            {...formItemLayout}
          >
            {getFieldDecorator("enabled", {
              rules: [{ required: true }],
              valuePropName: "checked",
              initialValue: record.hasOwnProperty('enabled') ? record.enabled : true
            })(
              <Switch>{messages('finance-1.key244')/*启用temp*/}</Switch>
            )}
          </Form.Item>
          <Priority
            top='TENANT'
            showSetOfBooks
            disabledTop={record.hasOwnProperty('id')}
            onChange={this.handlePriority}
            defaultValue={priority}
            showCompanyComponent={false}
            formItemLayout={formItemLayout}
            single={false}
            showCompany={false}
          />
          <Form.Item
            label={messages('finance-1.key275')/*借款类型代码*/}
            {...formItemLayout}
          >
            {getFieldDecorator("classCode", {
              rules: [{ required: true, message: messages('common.please.input')/*请输入*/ }],
              initialValue: record.classCode || 'JK001'
            })(
              <Input placeholder={'JK001'}/>
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-1.key276')/*借款类型名称*/}
            {...formItemLayout}
          >
            {getFieldDecorator("description", {
              rules: [{ required: true, message: messages('common.please.input')/*请输入*/ }],
              initialValue: { name: record.description, i18n: record.i18n ? record.i18n.description : [] }
            })(
              <InputLanguage
                placeholder={messages('common.max.characters.length',{arg1: 100})/*最多输入{arg1}个字符*/}
                maxLength={100}
              />
            )}
          </Form.Item>
          <h3 className='sub-title'>{messages('finance-1.key373')/*借款管控*/}</h3>
          {
            priority.levelCode !== 'TENANT' && (
              <div>
                <Form.Item
                  label={messages('finance-1.key374')/*借款金额控制范围*/}
                  {...formItemLayout}
                  extra={messages('finance-1.key375')/*前款不清，后款不借的统计范围*/}
                >
                  {getFieldDecorator("prePaymentCode", {
                    rules: [{ required: true, message: messages('common.select')/*请选择*/ }],
                    initialValue: record.prePaymentCode ? record.prePaymentCode + '' : undefined
                  })(
                    <Select placeholder={messages('common.select')/*请选择*/} onChange={this.handleChangeType}>
                      <Select.Option key={1001}>{messages('finance-1.key164')/*不控制*/}</Select.Option>
                      <Select.Option key={1002}>{messages('finance-1.key165')/*同类型控制*/}</Select.Option>
                      <Select.Option key={1003}>{messages('finance-1.key166')/*全控制*/}</Select.Option>
                    </Select>
                  )}
                </Form.Item>
                <Form.Item
                  label={messages('finance-1.key167')/*借款上限*/}
                  {...formItemLayout}
                >
                  <Space direction='vertical'>
                    <div className={'ant-form-extra'}>{messages('finance-1.key376')/*员工可借款累计金额，包括在途以及未还金额*/}</div>
                    <div>
                      <Button
                        type='primary'
                        onClick={() => this.handleAddLoanMax({ frontId: this.getRandomId() })}
                        disabled={!priority || getFieldValue('prePaymentCode') === '1001'}>{messages('common.create')/*新建*/}</Button>
                    </div>
                    <ResizeTable
                      columns={[
                        { title: messages('finance-1.key377')/*金额上限*/, dataIndex: 'amountMax', render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)) },
                        { title: messages('common.column.status')/*状态*/, dataIndex: 'enabled',
                          render: value => value ? <Badge text={messages('finance-1.key244')/*启用temp*/} status={'success'}/> :
                            <Badge text={messages('finance-1.key245')/*禁用temp*/} status={'error'}/>
                        }
                      ]}
                      dataSource={data}
                      onRow={record => ({
                        onClick: () => this.handleAddLoanMax(record)
                      })}
                      size="middle"
                      bordered
                      rowKey={record => record.id || record.frontId}
                    />
                    <div className={'ant-form-extra'}>{messages('finance-1.key378')/*供应商可借款累计金额，包括在途以及未还金额*/}</div>
                    <div>
                      <Button
                        type='primary'
                        onClick={() => this.handleAddVendorMax({ frontId: this.getRandomId() })}
                        disabled={!priority || getFieldValue('prePaymentCode') === '1001'}
                      >{messages('common.create')/*新建*/}</Button>
                    </div>
                    <ResizeTable
                      columns={[
                        { title: messages('finance-1.key377')/*金额上限*/, dataIndex: 'vendorAmountMax', render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)) },
                        { title: messages('common.column.status')/*状态*/, dataIndex: 'enabled',
                          render: value => value ? <Badge text={messages('finance-1.key244')/*启用temp*/} status={'success'}/> :
                            <Badge text={messages('finance-1.key245')/*禁用temp*/} status={'error'}/>
                        }
                      ]}
                      dataSource={vendorLoanAmountMaxDTOs}
                      onRow={record => ({
                        onClick: () => this.handleAddVendorMax(record)
                      })}
                      size="middle"
                      bordered
                      rowKey={record => record.id || record.frontId}
                    />
                  </Space>
                </Form.Item>
              </div>
            )
          }
          <Form.Item
            label={messages('finance-1.key379')/*员工超期未还不借*/}
            {...formItemLayout}
            extra={messages('finance-1.key380')/*已支付给员工且超期未还是否允许借款*/}
          >
            {getFieldDecorator("employeeOverdueLoanType", {
              rules: [{ required: true }],
              initialValue: record.hasOwnProperty('employeeOverdueLoanType') ? record.employeeOverdueLoanType : 1003
            })(
              <Radio.Group options={[
                { label: messages('finance-1.key164')/*不控制*/, value: 1001 },
                { label: messages('finance-1.key165')/*同类型控制*/, value: 1002 },
                { label: messages('finance-1.key166')/*全控制*/, value: 1003 }
              ]}/>
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-1.key381')/*是否允许代提借款*/}
            {...formItemLayout}
            extra={messages('finance-1.key382')/*控制借款单明细中收款人是否强制为申请人且不可修改*/}
          >
            {getFieldDecorator("allowAgentLoanBill", {
              rules: [{ required: true }],
              initialValue: record.hasOwnProperty('allowAgentLoanBill') ? record.allowAgentLoanBill : true
            })(
              <Radio.Group options={[
                { label: messages('common.yes')/*是*/, value: true },
                { label: messages('common.no')/*否*/, value: false }
              ]}/>
            )}
          </Form.Item>
          <h3 className='sub-title'>{messages('finance-1.key383')/*还款管控*/}</h3>
          <Form.Item
            label={messages('finance-1.key384')/*核销对象*/}
            {...formItemLayout}
            extra={messages('finance-1.key385')/*可以被哪些报销的付款类型核销*/}
          >
            {getFieldDecorator("writeOff", {
              rules: [{ required: true },{
                validator: (item, value, callback) => {
                  if (value.writeOffType === '2' && (!value.writeOffId || value.writeOffId.length === 0)) {
                    callback(messages('common.please.input')/*请输入*/);
                  }
                  callback();
                }
              }],
              initialValue: record.hasOwnProperty('id') ? {
                writeOffType: record.writeOffType,
                writeOffId: record.writeOffId ? record.writeOffId.split(',') : []
              } : { writeOffType: '1' }
            })(
              <WrapFormItem parser={value => value || {}}>
                {(onChange, value) => (
                  <Row gutter={10}>
                    <Col span={10}>
                      <Select
                        placeholder={messages('common.select')/*请选择*/}
                        value={value.writeOffType}
                        onChange={value => onChange({ writeOffType: value, writeOffId: [] })}
                      >
                        <Select.Option key={'1'}>{messages('common.all')/*全部*/}</Select.Option>
                        <Select.Option key={'2'}>{messages('finance-1.key386')/*部分*/}</Select.Option>
                      </Select>
                    </Col>
                    <Col span={14}>
                      <Select
                        notFoundContent={fetched ? messages('common.unmatched')/*无匹配结果*/ : <Spin size="small"/>}
                        placeholder={messages('common.select')/*请选择*/}
                        disabled={!priority || value.writeOffType === '1'}
                        mode="multiple"
                        value={value.writeOffId}
                        onChange={value => onChange({ writeOffId: value })}
                      >
                        {writeOffList.map(item => {
                          return <Select.Option key={item.id}>{item.description}</Select.Option>
                        })}
                      </Select>
                    </Col>
                  </Row>
                )}
              </WrapFormItem>
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-1.key387')/*强制核销*/}
            {...formItemLayout}
            extra={messages('finance-1.key388')/*欠款未还清时，不允许提交报销*/}
          >
            {getFieldDecorator("compulsoryWriteOff", {
              rules: [{ required: true }],
              initialValue: record.hasOwnProperty('compulsoryWriteOff') ? record.compulsoryWriteOff : false
            })(
              <Radio.Group options={[
                { label: messages('common.yes')/*是*/, value: true },
                { label: messages('common.no')/*否*/, value: false }
              ]}/>
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-1.key389')/*管控维度*/}
            {...formItemLayout}
            extra={messages('finance-1.key390')/*强制核销的管控维度，支持存在此类借款即必须核销，或此类借款必须超过计划还款日期才必须核销*/}
          >
            {getFieldDecorator('repaymentControlType', {
              rules: [{ required: true, message: messages('common.select')/*请选择*/ }],
              initialValue: record.hasOwnProperty('id') ? record.cashRepaymentTerm.repaymentControlType : '01'
            })(
              <Radio.Group options={[
                { label: messages('finance-1.key391')/*即时管控*/, value: '01' },
                { label: messages('finance-1.key392')/*超期管控*/, value: '02' }
              ]}/>
            )}
          </Form.Item>
          <Form.Item
            label={messages('finance-1.key393')/*还款期限*/}
            {...formItemLayout}
          >
            {getFieldDecorator("cashRepaymentTerm", {
              rules: [{ required: true, message: messages('common.select')/*请选择*/ }],
              initialValue: record.hasOwnProperty('id') ? record.cashRepaymentTerm : { repaymentType: '01' }
            })(
              <WrapFormItem parser={value => value || {}}>
                {(onChange, value) => (
                  <div>
                    <Radio.Group
                      value={value.repaymentType}
                      options={[
                        { label: messages('finance-1.key394')/*手动填写*/, value: '01' },
                        { label: messages('finance-1.key395')/*系统计算*/, value: '02' }
                      ]}
                      onChange={e => onChange({
                        repaymentType: e.target.value, planDateType: '01', planOverTime: 0, planOverUnit: '01'
                      })}
                    />
                    <div className={'ant-form-extra'}>{messages('finance-1.key396')/*员工借款时，计划还款日期支持手动填写，或系统计算，系统计算时，员工不可编辑，增加的参数可为空*/}</div>
                    {value.repaymentType === '02' && (
                      <Row>
                        <Col span={5}>{messages('finance-1.key25')/*计划还款日期*/}</Col>
                        <Col span={1}>=</Col>
                        <Col span={7} offset={1}>
                          <Select
                            placeholder={messages('common.select')/*请选择*/}
                            value={value.planDateType}
                            onChange={value => onChange({ planDateType: value })}
                          >
                            <Select.Option key={'01'}>{messages('finance-1.key151')/*最终提交日期*/}</Select.Option>
                            <Select.Option key={'02'}>{messages('finance-1.key152')/*审核通过日期*/}</Select.Option>
                            <Select.Option key={'03'}>{messages('finance-1.key153')/*最终付款日期*/}</Select.Option>
                          </Select>
                        </Col>
                        <Col span={1} offset={1}>+</Col>
                        <Col span={3} offset={1}>
                          <InputNumber onChange={value => onChange({ planOverTime: value })} min={0} value={value.planOverTime} style={{ width: '100%' }}/>
                        </Col>
                        <Col span={3} offset={1}>
                          <Select
                            placeholder={messages('common.select')/*请选择*/}
                            value={value.planOverUnit}
                            onChange={value => onChange({ planOverUnit: value })}
                          >
                            <Select.Option key={'01'}>{messages('finance-1.key154')/*天*/}</Select.Option>
                            <Select.Option key={'02'}>{messages('finance-1.key155')/*月*/}</Select.Option>
                            <Select.Option key={'03'}>{messages('finance-1.key156')/*年*/}</Select.Option>
                          </Select>
                        </Col>
                      </Row>
                    )}
                  </div>
                )}
              </WrapFormItem>
            )}
          </Form.Item>
          <div className='slide-footer'>
            <Button type='primary' onClick={this.handleSave} loading={saveLoading}>{messages('common.ok')/*确定*/}</Button>
            <Button onClick={() => close()}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </Form>
        <LoanMaxModal
          visible={visible}
          setOfBooksId={priority ? priority.levelOrgId : ''}
          record={loanMaxRecord}
          cancel={() => this.setState({ visible: false })}
          onOk={this.onOk}
        />
        <VendorMaxModal
          visible={vendorVisible}
          setOfBooksId={priority ? priority.levelOrgId : ''}
          record={vendorLoanMaxRecord}
          cancel={() => this.setState({ vendorVisible: false })}
          onOk={this.onVendorOk}
        />
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant
  }
}

export default Form.create()(LoanRule)
